package safety

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gitee.com/bobo-rs/creative-framework/pkg/encrypt"
	"gitee.com/bobo-rs/ecomp-analyzer-services/enums"
	"github.com/gogf/gf/v2/util/grand"
	"strconv"
	"time"
)

// Secret 哈希密钥
func (s *sSafety) Secret(tag enums.SafeTags) string {
	// 获取随机数
	return encrypt.NewM().MustEncryptString(s.Shuffle() + string(tag))
}

// Shuffle 随机数
func (s *sSafety) Shuffle() string {
	return strconv.FormatInt(time.Now().Unix(), 36) + grand.S(20)
}

// Decrypt 安全密钥解密，例如签名、手机号、身份证等
func (s *sSafety) Decrypt(ciphertext, secret string) ([]byte, error) {
	// 签名解密
	buffer, err := s.AESHandler(secret).DecryptString(ciphertext)
	if err != nil {
		return nil, fmt.Errorf(`安全密钥解密密文失败，%s`, err.Error())
	}
	return buffer, nil
}

// ToJson 转换为JSON
func (s *sSafety) ToJson(b []byte) *json.Decoder {
	return json.NewDecoder(bytes.NewBuffer(b))
}

// AESHandler AES加密处理
func (s *sSafety) AESHandler(secret string) *encrypt.AESHandler {
	return encrypt.NewAES().Cipher(encrypt.CipherHandler{
		Secret: secret,
	})
}
